package com.oracle.cmp.common;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = {"*.do", "*.jsp"})
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //Filter拦截请求后，就会执行这个方法
        //将参数对象转化为 Httpservletrequest和 Httpservletresponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //防止非法登录的验证
        //index.do、login.do
        String path = request.getServletPath();
        if (!"/index.do".equals(path) && !"/login.do".equals(path)) {
            if (request.getSession().getAttribute("user") == null) {
                request.getRequestDispatcher("/index.do").forward(request, response);
                return;
            }
        }
        //防浏览器缓存
        response.setHeader("Cache-Control","no-cache");
        response.setHeader("pragma","no-cache");
        response.setDateHeader("expries",-1);
        //filterChain代表的是，过滤器链
        //执行过滤器链后面的内容
        filterChain.doFilter(servletRequest, servletResponse);
    }


    @Override
    public void destroy() {

    }
}
